package com.neuedu.gui;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class FrameWithMenu extends JFrame {
    private JPanel currentPanel;  
  
    public FrameWithMenu() {  
        // 设置窗口标题和大小  
        setTitle("Frame With Menu");  
        setSize(400, 300);  
  
        // 创建菜单栏  
        JMenuBar menuBar = new JMenuBar();  
        setJMenuBar(menuBar);  
  
        // 创建菜单项  
        JMenu menu = new JMenu("Menu");  
        menuBar.add(menu);  
  
        // 创建子菜单项和相应的面板  
        JPanel panel1 = new JPanel();  
        panel1.add(new JLabel("Panel 1"));  
        JMenuItem menuItem1 = new JMenuItem("Show Panel 1");  
        menuItem1.addActionListener(new ActionListener() {
            @Override  
            public void actionPerformed(ActionEvent e) {
                currentPanel = panel1;  
                revalidate();  
                repaint();  
            }  
        });  
        menu.add(menuItem1);  
  
        JPanel panel2 = new JPanel();  
        panel2.add(new JLabel("Panel 2"));  
        JMenuItem menuItem2 = new JMenuItem("Show Panel 2");  
        menuItem2.addActionListener(new ActionListener() {  
            @Override  
            public void actionPerformed(ActionEvent e) {  
                currentPanel = panel2;
                revalidate();
                repaint();
                System.out.println("this = " + this);
                System.out.println("this = " + this);
                System.out.println("this = " + this);
            }
        });  
        menu.add(menuItem2);  
  
        // 默认显示第一个面板  
        currentPanel = panel1;  
        getContentPane().add(currentPanel);  
  
        // 设置关闭操作和可见性  
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        setVisible(true);  
    }  
  
    public static void main(String[] args) {  
        SwingUtilities.invokeLater(new Runnable() {  
            @Override  
            public void run() {  
                new FrameWithMenu();  
            }  
        });  
    }  
}